package com.chu.cloud.rabbit.direct;

import com.chu.cloud.rabbit.RabbitConstants;
import com.chu.cloud.rabbit.RabbitConstants.DirectQueueNameEnum;
import com.chu.cloud.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.UUID;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/3/30 15:28
 * @Description: 点对点 直接发送 rabbit mq 工具类,此方法没有出现exchange,是因为点对点自动使用
 * 了默认的exchange.amq.direct,事实上生产者是不能直接发送消息到队列上的,它只能发送
 * 给exchange,由exchange决定发送给哪个队列,exchange type决定了消息的最终处理
 * 方式: 一共有4种方式可供选择
 * 1.direct
 * 2.fanout
 * 3.topic
 * 4.headers
 */
@Component
@Slf4j
public class RabbitDirectSender {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendDirectMessage(DirectQueueNameEnum routingKey, Object message) {
        Assert.notNull(message, "rabbit message不能为空!");
        CorrelationData correlation = new CorrelationData(UUID.randomUUID().toString());
        this.rabbitTemplate.convertAndSend(routingKey.getValue(), message, correlation);
        log.info("direct send success delayqueue:{},message:{},correlationId:{}", routingKey.getValue(),
                JsonUtils.obj2json(message), correlation.getId());
    }

}
